package com.qindachang.bluetoothlelibrary.ui.test.Agree;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class BitConverterUtil {
    /**
     * @param strPart 字符串
     * @return 16进制字符串
     * @throws
     * @Title:string2HexString
     * @Description:字符串转16进制字符串
     */
    public static String string2HexString(String strPart) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < strPart.length(); i++) {
            int ch = (int) strPart.charAt(i);
            String strHex = Integer.toHexString(ch);
            hexString.append(strHex);
        }
        return hexString.toString();
    }

    /**
     * @param src 16进制字符串
     * @return 字节数组
     * @throws
     * @Title:hexString2String
     * @Description:16进制字符串转字符串
     */
    public static String hexString2String(String src) {
        String temp = "";
        for (int i = 0; i < src.length() / 2; i++) {
            temp = temp
                    + (char) Integer.valueOf(src.substring(i * 2, i * 2 + 2),
                    16).byteValue();
        }
        return temp;
    }

    /**
     * 将一个长整数转换位字节数组(8个字节)，b[0]存储高位字符，大端
     *
     * @param l 长整数
     * @return 代表长整数的字节数组
     */
    public static byte[] longToHexBytesBig(long l) {
        byte[] b = new byte[8];
        b[0] = (byte) (l >>> 56);
        b[1] = (byte) (l >>> 48);
        b[2] = (byte) (l >>> 40);
        b[3] = (byte) (l >>> 32);
        b[4] = (byte) (l >>> 24);
        b[5] = (byte) (l >>> 16);
        b[6] = (byte) (l >>> 8);
        b[7] = (byte) (l);
        return b;
    }

    /**
     * byte数组转double	 * @param bytes 8位byte数组	 * @param littleEndian 是否是小端模式	 * @return
     */
    public static double bytesToDouble(byte[] bytes, boolean littleEndian) {
        ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 8);
        if (littleEndian) {
            // ByteBuffer.order(ByteOrder) 方法指定字节序,即大小端模式(BIG_ENDIAN/LITTLE_ENDIAN)
            // ByteBuffer 默认为大端(BIG_ENDIAN)模式
            buffer.order(ByteOrder.LITTLE_ENDIAN);
        }
        long l = buffer.getLong();
        return Double.longBitsToDouble(l);
    }


    /**
     * double转byte数组，小端模式	 * @param d	 * @return
     */
    public static byte[] doubleToBytesLittle(double d) {
        long l = Double.doubleToLongBits(d);
        byte b[] = new byte[8];
        b[7] = (byte) (0xff & (l >> 56));
        b[6] = (byte) (0xff & (l >> 48));
        b[5] = (byte) (0xff & (l >> 40));
        b[4] = (byte) (0xff & (l >> 32));
        b[3] = (byte) (0xff & (l >> 24));
        b[2] = (byte) (0xff & (l >> 16));
        b[1] = (byte) (0xff & (l >> 8));
        b[0] = (byte) (0xff & l);
        return b;
    }

    /**
     * 以字节数组的形式返回指定的 64 位有符号整数值
     *
     * @param data 要转换的数字
     * @return 长度为 8 的字节数组
     */
    public static byte[] longToHexByteArray(long data) {
        byte[] bytes = new byte[8];
        if (isLittleEndian()) {
            bytes[0] = (byte) (data & 0xff);
            bytes[1] = (byte) ((data >> 8) & 0xff);
            bytes[2] = (byte) ((data >> 16) & 0xff);
            bytes[3] = (byte) ((data >> 24) & 0xff);
            bytes[4] = (byte) ((data >> 32) & 0xff);
            bytes[5] = (byte) ((data >> 40) & 0xff);
            bytes[6] = (byte) ((data >> 48) & 0xff);
            bytes[7] = (byte) ((data >> 56) & 0xff);
        } else {
            bytes[7] = (byte) (data & 0xff);
            bytes[6] = (byte) ((data >> 8) & 0xff);
            bytes[5] = (byte) ((data >> 16) & 0xff);
            bytes[4] = (byte) ((data >> 24) & 0xff);
            bytes[3] = (byte) ((data >> 32) & 0xff);
            bytes[2] = (byte) ((data >> 40) & 0xff);
            bytes[1] = (byte) ((data >> 48) & 0xff);
            bytes[0] = (byte) ((data >> 56) & 0xff);
        }
        return bytes;
    }

    /**
     * double转byte数组      double占8字节  ， 一个byte占一个字节
     *
     * @param d
     * @return
     */
    public static byte[] doubleToBytes(double d) {
        //根据 IEEE 754 浮点“双精度格式”位布局，返回指定浮点值的表示形式，并保留 NaN 值。
        Long value = Double.doubleToRawLongBits(d);
        byte[] b = new byte[8];
        for (int i = 0; i < 8; i++) {
            b[i] = (byte) ((value >> 8 * i) & 0xff);
        }
        return b;
    }

    /**
     * byte 转double
     *
     * @param arr
     * @return
     */
    public static double bytesToDouble(byte[] arr) {
        long value = 0;
        for (int i = 0; i < 8; i++) {
            value |= ((long) (arr[i] & 0xff)) << (8 * i);
        }
        return Double.longBitsToDouble(value);
    }

    //bool转byte
    public static byte[] booleanToByte(boolean val) {
        byte[] b = new byte[1];
        if (val) {
            b[0] = 1;
        }
        return b;
    }

    /*输入16进制byte[]输出16进制字符串*/
    public static String byteArrayToHexStr(byte[] byteArray) {
        if (byteArray == null) {
            return null;
        }
        char[] hexArray = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[byteArray.length * 2];
        for (int j = 0; j < byteArray.length; j++) {
            int v = byteArray[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    /**
     * 字符串转十六进制字符数组
     *
     * @param str
     * @param size 分配内存空间字节长度
     * @return
     * @throws Exception
     */
    public static byte[] stringToHexByteArray(String str, int size, Boolean bLeft) throws
            Exception {
        // 用于接收转换结果
        String hexString = "";
        // 1.校验是否包含特殊字符内容
        // java特殊转义符
        String[] escapeArray = {"\b", "\t", "\n", "\f", "\r", "\'", "\"", "\\"};
        // 用于校验参数是否包含特殊转义符
        boolean flag = false;
        // 迭代
        for (String esacapeStr : escapeArray) {
            // 一真则真
            if (str.contains(esacapeStr)) {
                flag = true;
                break;// 终止循环
            }
        }
        // 包含特殊字符
        if (flag) throw new Exception("参数字符串不能包含转义字符！");
        // 16进制字符
        char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        StringBuilder sb = new StringBuilder();
        // String--&gt;byte[]
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(hexArray[bit]);
            bit = bs[i] & 0x0f;
            sb.append(hexArray[bit]);
        }
        if (bLeft) {
            hexString = addLeftZeroForNum(sb.toString(), 2 * size);
        } else {
            hexString = addRightZeroForNum(sb.toString(), 2 * size);
        }
        return hexToByteArray(hexString);
    }

    /**
     * 十进制转16进制字符数组
     *
     * @param num
     * @return
     */
    public static byte[] intToHexByteArray(int num, int size) throws Exception {
        String hexString = Integer.toHexString(num);
        hexString = addLeftZeroForNum(hexString, 2 * size);
        return hexToByteArray(hexString);
    }

    /**
     * 十六进制转十进制
     * @param array
     * @return
     */
    public static int hexByteArrayToInt(byte[] array) {
        String hexString = byteArrayToHexStr(array);
        int inJTFingerLockAddress = Integer.valueOf(hexString, 16);
        return inJTFingerLockAddress;
    }

    /**
     * 十六进制左补零
     *
     * @param str
     * @param size
     * @return
     */
    public static String addLeftZeroForNum(String str, int size) {
        int strLen = str.length();
        StringBuffer sb = null;
        while (strLen < size) {
            sb = new StringBuffer();
            sb.append("0").append(str);// 左补0
            str = sb.toString();
            strLen = str.length();
        }
        return str;
    }

    /**
     * 十六进制右补零
     *
     * @param str
     * @param size
     * @return
     */
    public static String addRightZeroForNum(String str, int size) {
        int strLen = str.length();
        StringBuffer sb = null;
        while (strLen < size) {
            sb = new StringBuffer();
            sb.append(str).append("0");//右补0
            str = sb.toString();
            strLen = str.length();
        }
        return str;
    }

    /**
     * Hex字符串转byte
     *
     * @param inHex 待转换的Hex字符串
     * @return 转换后的byte
     */
    public static byte hexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    /**
     * hex字符串转byte数组
     *
     * @param inHex 待转换的Hex字符串
     * @return 转换后的byte数组结果
     */
    public static byte[] hexToByteArray(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            //奇数
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {
            //偶数
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    /**
     * byte数组转换为int整数
     *
     * @param bytes byte数组
     * @param off   开始位置
     * @return int整数
     */
    public static int byte4ToInt(byte[] bytes, int off) {
        int b0 = bytes[off] & 0xFF;
        int b1 = bytes[off + 1] & 0xFF;
        int b2 = bytes[off + 2] & 0xFF;
        int b3 = bytes[off + 3] & 0xFF;
        return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
    }


    /*
     * 字节数组转字符串
     */
    public static String bytes2String(byte[] b) throws UnsupportedEncodingException {
        String r = null;
        r = new String(b, "GBK");
        return r;
    }

    /*
     * 字符串转字节组
     */
    public static byte[] string2Bytes(String s) {
        byte[] r = s.getBytes();
        return r;
    }


    /**
     * 数组拷贝
     *
     * @param bytes      字节数组
     * @param startIndex 起始下标
     * @param length     拷贝长度
     * @return 指定长度的字节数组
     */
    private static byte[] copyFrom(byte[] bytes, int startIndex, int length) {
        // Arrays.copyOfRange(bytes, startIndex, startIndex + length);
        byte[] bits = new byte[length];
        for (int i = startIndex, j = 0; i < bytes.length && j < bits.length; i++, j++) {
            bits[j] = bytes[i];
        }
        return bits;
    }

    /**
     * 返回由字节数组转换来的 64 位有符号整数
     *
     * @param bytes 字节数组
     * @return 由八个字节构成的 64 位有符号整数
     */
    public static long toLong(byte[] bytes) {
        if (isLittleEndian()) {
            return (0xffL & (long) bytes[0])
                    | (0xff00L & ((long) bytes[1] << 8))
                    | (0xff0000L & ((long) bytes[2] << 16))
                    | (0xff000000L & ((long) bytes[3] << 24))
                    | (0xff00000000L & ((long) bytes[4] << 32))
                    | (0xff0000000000L & ((long) bytes[5] << 40))
                    | (0xff000000000000L & ((long) bytes[6] << 48))
                    | (0xff00000000000000L & ((long) bytes[7] << 56));
        } else {
            return (0xffL & (long) bytes[7])
                    | (0xff00L & ((long) bytes[6] << 8))
                    | (0xff0000L & ((long) bytes[5] << 16))
                    | (0xff000000L & ((long) bytes[4] << 24))
                    | (0xff00000000L & ((long) bytes[3] << 32))
                    | (0xff0000000000L & ((long) bytes[2] << 40))
                    | (0xff000000000000L & ((long) bytes[1] << 48))
                    | (0xff00000000000000L & ((long) bytes[0] << 56));
        }
    }

    /**
     * 返回由字节数组中的指定的八个字节转换来的 64 位有符号整数
     *
     * @param bytes      字节数组
     * @param startIndex 起始下标
     * @return 由八个字节构成的 64 位有符号整数
     */
    public static long toLong(byte[] bytes, int startIndex) {
        return toLong(copyFrom(bytes, startIndex, 8));
    }

    /**
     * 返回由字节数组转换来的双精度浮点数
     *
     * @param bytes 字节数组
     * @return 由八个字节构成的双精度浮点数
     */
    public static double toDouble(byte[] bytes) {
        return Double.longBitsToDouble(toLong(bytes));
    }

    /**
     * 返回由字节数组中的指定的八个字节转换来的双精度浮点数
     *
     * @param bytes      字节数组
     * @param startIndex 起始下标
     * @return 由八个字节构成的双精度浮点数
     */
    public static double toDouble(byte[] bytes, int startIndex) {
        return Double.longBitsToDouble(toLong(copyFrom(bytes, startIndex, 8)));
    }


    /**
     * 判断 CPU Endian 是否为 Little
     *
     * @return 判断结果
     */
    private static boolean isLittleEndian() {
        return ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN;
    }


    /**
     * 解码相关
     *
     * @param src
     * @param begin
     * @param count
     * @return
     */
    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        for (int i = begin; i < begin + count; i++) bs[i - begin] = src[i];
        return bs;
    }

    /**
     * byte[] -> short类型
     * byte数组转short src是byte数组名 offset是开始索引
     */
    public static short bytesToShort(byte[] src, int offset) {
        short value;
        value = (short) (((src[offset + 1] & 0xFF) << 8) | (src[offset + 0] & 0xFF));
        return value;
    }

    /**
     * byte数组转int  src是byte数组名 offset是开始索引
     *
     * @param src
     * @param offset
     * @return
     */
    public static int bytesToInt(byte[] src, int offset) {
        int value;
        value = (int) ((src[offset + 3] & 0xFF << 24) | ((src[offset + 2] & 0xFF) << 16) | ((src[offset + 1] & 0xFF) << 8) | ((src[offset + 0] & 0xFF) << 0));
        return value;
    }

    /**
     * byte数组转long  src是byte数组名 offset是开始索引
     *
     * @param src
     * @param offset
     * @return
     */
    public static long bytesToLong(byte[] src, int offset) {
        long value;
        value = (long) (((long) src[offset + 7] & 0xFF << 56) | ((src[offset + 6] & 0xFF) << 48) | ((long) src[offset + 5] & 0xFF << 40) | ((src[offset + 4] & 0xFF) << 32) | ((long) src[offset + 3] & 0xFF << 24) | ((src[offset + 2] & 0xFF) << 16) | ((src[offset + 1] & 0xFF) << 8) | ((src[offset + 0] & 0xFF) << 0));
        return value;
    }


    /**
     * 无符号整数的转换 ip，port
     *
     * @param num
     * @return
     */
    public static long getUnsignedInt(int num) {
        return num & 0xFFFFFF;
    }

    public static int getUnsignedShort(short num) {
        return num & 0xFFFF;
    }

    public static int getUnsignedByte(byte num) {
        return num & 0x0FF;
    }

    /**
     * 转字符串
     *
     * @param buf
     * @param offset
     * @return
     */
    public static String byteToString(byte buf[], int offset) {
        int pos = offset;
        for (; offset < buf.length; offset++)
            if (buf[offset] == 0)
                break;
        if (offset > pos)
            offset--;
        else if (offset == pos)
            return "";
        int len = (offset - pos) + 1;
        byte bb[] = new byte[len];
        System.arraycopy(buf, pos, bb, 0, len);
        String str = new String(bb);
        return str;
    }

}
